<?php
declare(strict_types=1);

namespace Zms\Unit;

use Exception;

/**
 * 数据加密解密
 */
class Encryption
{
    /**
     * 默认密钥
     */
    const KEY = 'B763679B31C8CD7C483D4BB8385EAA24';

    /**
     * 数据加密
     * @param mixed $data
     * @param string $key
     * @return string
     */
    public static function encrypt($data, $key = self::KEY): string
    {
        $data = openssl_encrypt(json_encode(['data' => $data]), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return base64_encode($data);
    }


    /**
     * 数据解密
     * @param string $str
     * @param string|null $key
     * @return mixed|null
     */
    public static function decrypt($str, $key = self::KEY)
    {
        try {
            $data = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
            if (!$data) return null;
            $arr = Json::decode($data);
            return $arr['data'] ?? null;
        } catch (Exception $exception) {
            return null;
        }
    }
}